package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.entity.TJldzpcom;
import com.wit.witmg.entity.TPolling;
import com.wit.witmg.mapper.TPollingMapper;
import com.wit.witmg.service.ITJldzpcomService;
import com.wit.witmg.service.ITPollingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import com.wit.witmg.util.ModbusReader;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 轮询启用表 服务实现类
 * </p>
 *
 * @author bob
 * @since 2025-10-20
 */
@Service
public class TPollingServiceImpl extends ServiceImpl<TPollingMapper, TPolling> implements ITPollingService {

    @Resource
    private ITJldzpcomService jlService;

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
    @Override
    public Object add(HttpServletRequest request, String json) {
//        json="{\"dt0\":1760929955,\"dt1\":1760931000,\"mid\":30,\"tp\":\"工序A\",\"ph\":\"批次001\",\"xh\":\"1\",\"htp\":\"http://api.example.com/data\"}";
        TPolling t = JSON.parseObject(json, TPolling.class);
        if(t==null || t.getDt0()==null || t.getDt1()==null){
            return JsonResult.error(ErrorCode.ERR_200);
        }
        if(t.getDt0()>t.getDt1()){
            return JsonResult.error(ErrorCode.ERR_200);
        }
        if(t.getPh()==null || t.getTp()==null){
            return JsonResult.error(ErrorCode.ERR_200);
        }
        TPolling t1 = getOne(new QueryWrapper<TPolling>().orderByDesc("dt1").last("limit 1"));
        if(t1!=null){
            if(t1.getDt1()>t.getDt0()){
                return JsonResult.error(ErrorCode.ERR_407);
            }
        }
        if(save(t)){
            startPolling(t);
            return JsonResult.success(t);
        }
        return JsonResult.error(ErrorCode.ERR_504);
    }

    @Override
    public Object get(HttpServletRequest request) {
        return JsonResult.success(list(new QueryWrapper<TPolling>().orderByDesc("id")));
    }

    /**
     * 启动轮询任务
     */
    @Async
    public void startPolling(TPolling polling) {
        long startTime = polling.getDt0()*1000;
        long endTime = polling.getDt1()*1000;
        Integer interval = polling.getMid();

        long initialDelay = startTime - System.currentTimeMillis();
        if (initialDelay < 0) {
            initialDelay = 0;
        }

        long period = interval * 1000L; // 转换为毫秒

        Runnable pollingTask = () -> {
            // 检查是否超过结束时间
            if (System.currentTimeMillis() > endTime) {
                scheduler.shutdown();
                return;
            }

            // 执行数据查询和插入操作
            executePollingTask(polling);
        };

        // 启动定时任务
        scheduler.scheduleAtFixedRate(pollingTask, initialDelay, period, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行轮询任务：查询数据并插入到目标表
     */
    private void executePollingTask(TPolling polling) {
        ModbusReader reader = new ModbusReader("60.190.91.134", 5001, 1);
        try {
            if (reader.connect()) {
                System.out.println("TCP连接成功");
                // 读取输入寄存器 (地址1开始，读取2个寄存器)
                int[] inputRegs = reader.readInputRegisters(1, 10);
                TJldzpcom t = new TJldzpcom();
                t.setPh(polling.getPh());
                t.setXh(polling.getXh());
                t.setTp(polling.getTp());
                t.setDate(new Date());
                t.setTec(Arrays.toString(inputRegs));
                jlService.save(t);
            }

        } catch (IOException e) {
//            reader.disconnect();
        } finally {
            reader.disconnect();
        }

    }

    /**
     * 停止所有轮询任务
     */
    public void stopAllPolling() {
        scheduler.shutdown();
    }
}
